<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { useRouter } from 'vue-router'
// import TwoStepDingxiang from '@/components/TwoStepDingxiang/TwoStepDingxiang.vue'
import pdrLogo from '@/assets/pdr-logo.png'
import lpLogo from '@/assets/lp-logo.png'
import { message } from 'ant-design-vue'
import { useBrandStore } from '@/store/modules/brand'
import * as workPlaceWeChatApi from '@/api/workPlaceWeChat'

import erweimaLoginImg from '@/assets/login-erweima.png'

const router = useRouter()
const userStore = useUserStore()

const brandStore = useBrandStore()

const twoStepDingxiang = ref()

let labelCol = { span: 4 }
let loginForm = ref<HTMLElement | null>(null)
interface FormState {
  userName: string | number
  passWord: string | number
}
const formState = ref<FormState>({
  userName: '',
  passWord: '',
})

const handleSubmit = async () => {
  // twoStepDingxiang.value.showModal()

  let params = {
    userName: formState.value.userName,
    password: formState.value.passWord,
  }
  await userStore.login(params)
  router.push({ path: '/' })
}

const onFinish = async (values: any) => {
  const deviceType = checkDeviceType()
  if (deviceType !== 'Desktop') {
    // 如果是移动设备
    message.info('请在电脑上打开')
    router.push('no-content')
  } else {
    // 继续执行登录逻辑
    dxTokenRef.value.callbackFn()
  }

  // let params = {
  //   userName: formState.value.userName,
  //   password: formState.value.passWord,
  // }
  // await userStore.login(params)
  // router.push({ path: '/' })
}

const isPhoneNumber = (rule: any, value: any, callback: any) => {
  const phoneRegex = /^1[3-9]\d{9}$/ // 假设这是中国的手机号格式
  const numberGex = /^[0-9]+$/
  if (!phoneRegex.test(value) && value && numberGex.test(value)) {
    callback(new Error('请输入有效的手机号！'))
  } else {
    callback()
  }
}

// 注册账号
const register = () => {
  router.push({ path: '/register' })
}

// 忘记密码
const forgotPwd = () => {
  router.push({ path: '/forgotpwd' })
}

// 顶象验证码
let dxTokenRef = ref()
const getToken = async (e: any) => {
  let params = {
    userName: formState.value.userName,
    password: formState.value.passWord,
  }
  await userStore.login(params)
  router.push({ path: '/' })
}

let activeTab = ref<number>(1)
const changeTab = (e: number) => {
  activeTab.value = e
  if (activeTab.value == 2) router.push({ path: '/register' })
}

// 检测登录设备
const checkDeviceType = () => {
  const userAgent = navigator.userAgent || navigator.vendor || window.opera

  // 简单的设备检测逻辑
  if (/windows phone/i.test(userAgent)) {
    return 'Windows Phone'
  }
  if (/android/i.test(userAgent)) {
    return 'Android'
  }
  if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
    return 'iOS'
  }
  return 'Desktop'
}

onMounted(() => {
  const deviceType = checkDeviceType()
  if (deviceType !== 'Desktop') {
    // 如果是移动设备
    message.info('请在电脑上打开')
    router.push('no-content')
  }
})

const bindWeChat = async (code: string) => {
  try {
    let {
      state,
      data,
      message: msg,
    } = await workPlaceWeChatApi.addPublicWechatUserRelevancy({ code })
    if (state === 200) {
      message.success('绑定成功')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('绑定失败，请扫码重试~')
  }
}

let erweimaLodinFlag = ref(true)
const erweimaLogin = () => {
  console.log('二维码登录')
  erweimaLodinFlag.value = erweimaLodinFlag.value
    ? (erweimaLodinFlag.value = false)
    : (erweimaLodinFlag.value = true)

  if (erweimaLodinFlag.value) {
    let url = window.location.href
    const hashUrl = url.split('#')[1] // 获取#后面的部分
    const queryString = hashUrl.split('?')[1] // 获取?后面的查询字符串

    // 使用URLSearchParams对象来解析查询字符串
    const params = new URLSearchParams(queryString)
    let code = ''
    code = params.get('code') as string

    console.log('code=', code)

    if (code) {
      bindWeChat(code)
    }
  }
}

//#region 微信扫码登录
const AppID = 'wxc087a218643a7b09' // 票达人CRM

let local = `http://pdr-web-v2.liangpiao.net.cn/cdx2.html` // 线上 - 重定向配置（微信扫码后，会重定向到这个地址）

if (window.location.origin.indexOf('192.168') != -1) {
  local = `http://pdr-web-v2.liangpiao.net.cn/cdx1.html?id=123&name=dnfdnf` // 开发 - 重定向配置（微信扫码后，会重定向到这个地址）
  // local = `http://pdr-web.liangpiao.net.cn/cdx1.html` // 测试环境 - 重定向配置（微信扫码后，会重定向到这个地址）
}

local = encodeURIComponent(local)

let url = local

let wxLoginContainer = ref()

const script = document.createElement('script')
script.src = 'http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
script.async = true // 设置为异步加载，这样不会阻塞页面的其他资源加载

// 当脚本加载完成后，执行回调函数
script.onload = () => {
  // 检查 WxLogin 函数是否存在，以确保脚本已正确加载
  if (typeof WxLogin === 'function' && wxLoginContainer.value) {
    // console.log('wxLoginContainer=', wxLoginContainer.value.id)

    // 初始化微信登录按钮
    new WxLogin({
      id: wxLoginContainer.value.id, // 容器的ID
      appid: AppID,
      scope: 'snsapi_login',
      redirect_uri: url,
      state: 'STATE', // 可选参数，用于防止csrf攻击
      // style: 'black', // 可选，按钮样式，默认black
      // href: '', // 可选，自定义样式链接
      href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlIHsNCiAgICBkaXNwbGF5OiBub25lOw0KfQ0KLmltcG93ZXJCb3ggLnFyY29kZS5saWdodEJvcmRlciB7DQogICAgd2lkdGg6IDIwMHB4Ow0KfQ==',
    })
  } else {
    console.error('WxLogin function is not defined. Make sure the script is loaded correctly.')
  }
}

// 将 script 元素添加到页面的 head 或 body 中
document.head.appendChild(script)
//#endregion 微信扫码登录
</script>

<template>
  <div class="main-app">
    <div class="main-logo">
      <div class="lp-logo" v-if="brandStore.title_1">
        <img :src="brandStore.logo_1" />
        <span style="color: #6d36bb; font-weight: bolder; margin-left: 4px; font-size: 15px">
          {{ brandStore.title_1 }}
        </span>
      </div>
      <div class="vertical-line" v-if="brandStore.title_2"></div>
      <div class="pdr-logo" v-if="brandStore.title_2">
        <img :src="brandStore.logo_2" />
        <span style="color: black; font-weight: bolder; margin-left: 4px; font-size: 15px">
          {{ brandStore.title_2 }}
        </span>
      </div>
    </div>

    <div class="title-desc">
      <div style="letter-spacing: 4px">
        <i>{{ brandStore.description_1 }}</i>
      </div>
      <div style="letter-spacing: 4px">
        <i>{{ brandStore.description_2 }}</i>
      </div>
      <div style="font-weight: 400; font-size: 18px; letter-spacing: 10px">用技术为运营提效</div>
    </div>

    <div class="login-box">
      <!-- 二维码登录 -->
      <!-- <div class="erweima-lodin" @click="erweimaLogin">
        <img :src="erweimaLoginImg" alt="" />
      </div> -->

      <div style="width: 18rem; height: 18rem; margin-left: -10px;" v-show="!erweimaLodinFlag">
        <div ref="wxLoginContainer" id="wxLoginContainer"></div>
      </div>

      <a-form
        v-show="erweimaLodinFlag"
        style="width: 18rem"
        ref="loginForm"
        :model="formState"
        :label-col="labelCol"
        autocomplete="off"
        scrollToFirstError
        @finish="onFinish"
      >
        <div class="tabs">
          <div class="left-box" @click="changeTab(1)">
            <div :class="{ 'password-login': activeTab === 1 }">密码登录</div>
          </div>
          <div class="right-box" @click="changeTab(2)">
            <span :class="{ 'register-account': activeTab === 2 }">注册账号</span>
          </div>
        </div>

        <a-form-item
          name="userName"
          :rules="[
            { required: true, message: '请输入用户名!' },
            { validator: isPhoneNumber, trigger: 'blur' },
            { pattern: /^[0-9]+$/, message: '用户名只能包含数字!' },
          ]"
        >
          <a-input v-model:value="formState.userName" placeholder="请输入用户名" autocomplete="off">
            <template #prefix><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input>
        </a-form-item>

        <a-form-item name="passWord" :rules="[{ required: true, message: '请输入密码!' }]">
          <a-input-password
            v-model:value="formState.passWord"
            placeholder="请输入密码"
            autocomplete="off"
          >
            <template #prefix><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
          </a-input-password>
        </a-form-item>

        <a-form-item style="text-align: center">
          <a-button style="width: 18rem" type="primary" html-type="submit" block>登 录</a-button>
        </a-form-item>

        <div style="width: 18rem; display: flex">
          <p style="flex: 1">
            <a @click="forgotPwd">忘记密码</a>
          </p>
          <p style="flex: 1; text-align: right">
            <a @click="register">注册账户</a>
          </p>
        </div>
      </a-form>
      <!-- <TwoStepDingxiang ref="twoStepDingxiang"></TwoStepDingxiang> -->
    </div>
  </div>

  <DxToken ref="dxTokenRef" @onSuccessfully="getToken"></DxToken>

  <div class="footer-text">
    <a>
      {{ brandStore.recordNumber }}
    </a>
  </div>
</template>

<style scoped lang="less">
.footer-text {
  position: fixed;
  bottom: 10px;
  left: 0;
  height: 50px;
  line-height: 50px;
  width: 100%;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.main-app {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('@/assets/pdr-bg.png');
  background-size: 100% 100%;
}

.main-logo {
  position: fixed;
  top: 10px;
  left: 10px;
  display: flex;
  height: 50px;
  width: 300px;
  // background: pink;

  .lp-logo {
    // width: 140px;
    flex: 1;
    height: 40px;

    img {
      height: 100%;
    }
  }

  .pdr-logo {
    flex: 1;
    height: 40px;

    img {
      height: 100%;
    }
  }

  .vertical-line {
    width: 2px; /* 竖线宽度 */
    height: 16px; /* 竖线高度，根据需要调整 */
    background-color: #999999; /* 竖线颜色，根据需要调整 */
    margin-top: 10px;
    margin-right: 28px;
  }
}

.login-box {
  display: flex;
  border-radius: 0.4rem;

  position: fixed;
  top: 30%;
  right: 14%;

  background: #ffffff;
  padding-top: 2rem;
  padding-bottom: 1rem;
  padding-left: 2rem;
  padding-right: 2rem;
  box-shadow: 0 10px 20px rgb(165 157 157 / 19%), 0 6px 6px rgb(255 255 255 / 23%);
}

@media (max-width: 600px) {
  /* 你可以根据需要调整这个断点 */
  .login-box {
    right: auto; /* 取消右对齐 */
    left: 50%; /* 将左边距设置为50% */
    transform: translateX(-50%); /* 向左移动自身宽度的50%，以实现居中 */
  }

  .title-desc {
    display: none;
  }
}

.tabs {
  display: flex;
  margin-bottom: 30px;
  font-weight: bolder;
  cursor: pointer;

  .left-box {
    flex: 1;
    text-align: right;
    padding-right: 1rem;
  }
  .right-box {
    flex: 1;
    padding-left: 1rem;
  }
}

.password-login {
  // 设置相对定位，以便伪元素可以相对于它定位
  position: relative;
  // 使得伪元素可以基于文本宽度来定位
  display: inline-block;
}

.password-login::after {
  // 伪元素的内容为空
  content: '';
  position: absolute;
  // 根据需要调整这个值以对齐到“码登”下方
  bottom: -2px;
  // 初始位置在元素宽度的中间
  left: 50%;
  // 短横线的宽高
  width: 30px;
  height: 2px;
  background-color: #1890ff;
  transform: translateX(-50%);
}

.register-account {
  position: relative;
  display: inline-block;
}

.register-account::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  width: 30px;
  height: 2px;
  background-color: #1890ff;
  transform: translateX(-50%);
}

.title-desc {
  position: fixed;
  top: 36%;
  left: 16%;
  color: #163997;
  font-size: 36px;
  font-weight: bolder;
  min-width: 600px;
  width: 600px;
  overflow: hidden;
}

.erweima-lodin {
  cursor: pointer;
  position: absolute;
  width: 66px;
  height: 66px;
  // background-color: aqua;
  left: 0;
  top: 0;

  img {
    width: 100%;
    height: 100%;
  }
}
</style>
